package com.zxt.web.handler;

import com.zxt.bean.Result;
import com.zxt.bean.ResultCode;
import com.zxt.bean.ServiceException;
import com.zxt.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


/**
 * 集中处理所有异常
 */
@Slf4j
@ResponseBody
@RestControllerAdvice(basePackages = "com.zxt.*")
@Deprecated //弃用注解
public class ExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handleVaildException(MethodArgumentNotValidException e) {

        log.info("数据校验出现问题{},异常类型{}", e.getMessage(), e.getClass());

        BindingResult result = e.getBindingResult();
        Map<String, String> map = new HashMap<>();

        result.getFieldErrors().forEach((item) -> {
            //FieldError 获取到的错误提示
            String defaultMessage = item.getDefaultMessage();
            //获取发生错误的属性名
            String field = item.getField();
            map.put(field, defaultMessage);
        });

        return Result.newError(ResultCode.API_INVLID_DATA_FORMAT, ResultCode.API_INVLID_DATA_FORMAT.getDesc());
    }

    @ExceptionHandler(value = Throwable.class)
    public Result handleException(Throwable e) {
        log.info("出现异常{},异常类型{}", e.getMessage(), e.getClass());
        e.printStackTrace();

        if (e instanceof ServiceException) {
            Integer code = ((ServiceException) e).getCode();
            String message = e.getMessage();
            if (Objects.nonNull(code) && StringUtils.isNotEmpty(message)) {
                return Result.newError(code, message);
            }
        }

        return Result.newError(ResultCode.SYS_ERROR.getCode(), ResultCode.SYS_ERROR.getDesc());
    }


}
